package com.example.im.ui.activity

import android.content.Intent
import android.view.MenuItem
import android.view.View
import androidx.appcompat.app.AlertDialog
import androidx.fragment.app.Fragment
import com.example.im.R
import com.example.im.callback.OnClickRoomListener
import com.example.im.ui.fragment.RoomCentreFragment
import com.example.im.ui.fragment.RoomCreateFragment
import com.example.im.ui.fragment.RoomInviteFragment
import com.example.im.common.Constants
import com.example.im.common.Enumerate
import com.example.im.common.ImApplication
import com.example.im.entity.EventBusData
import com.example.im.entity.FriendOrRoom
import com.example.im.mvp.presenter.RoomPresenter
import com.example.im.mvp.view.IRoomView
import com.example.im.ui.abstracts.AbstractBaseActivity
import com.example.im.ui.fragment.RoomOwnerFragment
import com.example.im.xmpp.IMConnection
import kotlinx.android.synthetic.main.include_toolbar.*
import org.greenrobot.eventbus.EventBus
import org.jivesoftware.smackx.muc.Affiliate

class RoomActivity : AbstractBaseActivity<RoomPresenter>(), IRoomView, OnClickRoomListener {

    private var room: FriendOrRoom? = null

    private var mOnToRoomCentreFragment: OnToRoomCentreFragment? = null

    interface OnToRoomCentreFragment {
        fun onRoomUser(owners: MutableList<FriendOrRoom>)
    }

    override val layoutId: Int
        get() = R.layout.activity_room

    override fun onAttachFragment(fragment: Fragment) {
        super.onAttachFragment(fragment)
        when (fragment) {
            is RoomCentreFragment -> {
                tv_toolbar_title.text = "群聊信息"
                mOnToRoomCentreFragment = fragment
            }
            is RoomCreateFragment -> tv_toolbar_title.text = "创建群聊"
            is RoomInviteFragment -> tv_toolbar_title.text = "邀请好友"
            is RoomOwnerFragment -> tv_toolbar_title.text = "群聊成员"
        }
    }

    override fun initView() {
        supportActionBar?.setDisplayHomeAsUpEnabled(true)

        val toFragment = intent.getIntExtra(Constants.BUNDLE_T0_ROOM_MARK, 0)
        val transaction = supportFragmentManager.beginTransaction()
        if (toFragment == Constants.BUNDLE_T0_ROOM_MARK_CENTRE) {
            room = intent.getSerializableExtra(Constants.BUNDLE_T0_ROOM_DATA) as FriendOrRoom?
            transaction.replace(R.id.frame_layout, RoomCentreFragment.newInstance(room!!))
        } else {
            transaction.replace(R.id.frame_layout, RoomCreateFragment.newInstance())
        }
        transaction.commit()
    }

    override fun initPresenter() {
        mPresenter = RoomPresenter(this, this)
    }

    override fun onOptionsItemSelected(item: MenuItem?): Boolean {
        when (item?.itemId) {
            android.R.id.home -> {
                onBackPressed()
            }
        }
        return super.onOptionsItemSelected(item)
    }

    /**
     * 群创建-点击事件
     * */
    override fun onClickCreate(view: View, name: String) {
        mPresenter!!.roomCreate(name)
    }

    /**
     * 群邀请好友-点击事件
     * */
    override fun onClickInvite(view: View, friends: List<FriendOrRoom>) {
        mPresenter!!.roomInvite(room!!.account!!, friends)
    }

    /**
     * 群全部成员-点击事件
     * */
    override fun onClickUserTotal(view: View, owners: ArrayList<FriendOrRoom>) {
        val transaction = supportFragmentManager.beginTransaction()
        transaction.add(R.id.frame_layout, RoomOwnerFragment.newInstance(owners))
        transaction.addToBackStack(null)
        transaction.commit()
    }

    override fun onClickUserKick(view: View, friends: ArrayList<FriendOrRoom>) {
        mPresenter!!.roomKick(room!!.account!!, friends)
    }

    /**
     * 进入邀请好友界面-点击事件
     * */
    override fun onClickUserAdd(view: View) {
//        val transaction = supportFragmentManager.beginTransaction()
//        transaction.add(R.id.frame_layout, RoomInviteFragment.newInstance())
//        transaction.addToBackStack(null)
//        transaction.commit()
    }

    /**
     * 发送群聊天-点击事件
     * */
    override fun onClickSendChat(view: View, room: FriendOrRoom) {
        val intent = Intent(this, ChatActivity::class.java)
        intent.putExtra(Constants.BUNDLE_T0_CHAT_DATA, room)
        startActivity(intent)
        this.finish()
    }

    /**
     * 删除聊天数据-点击事件
     * */
    override fun onClickClearChat(view: View, room: FriendOrRoom) {
        val dialog = AlertDialog.Builder(this)
            .setTitle(room.nickname)
            .setMessage("是否清空聊天记录")
            .setPositiveButton("确定") { _, _ ->
                //通知聊天页面更新
                ImApplication.appDatabase().chatRecordLastDao()
                    .delete(room.id)
                val busData = EventBusData(
                    Enumerate.Handle.list_chat, Enumerate.Action.list_delete, room
                )
                EventBus.getDefault().post(busData)
            }
            .setNegativeButton("取消", null)
        dialog.show()
    }

    /**
     * 删除数据并退出群-点击事件
     * */
    override fun onClickClearExit(view: View, room: FriendOrRoom) {
        val dialog = AlertDialog.Builder(this)
            .setTitle(room.nickname)
            .setMessage("是否退出该群并删除聊天记录")
            .setPositiveButton("确定") { _, _ ->
                mPresenter!!.roomLeave(room)
            }
            .setNegativeButton("取消", null)
        dialog.show()
    }

    /**
     * 群聊信息页面加载完成调用
     * */
    override fun onInitAffiliate(room: FriendOrRoom) {
        mPresenter!!.roomUser(room)
    }


    /**
     * 群创建成功调用
     * */
    override fun onRoomCreateSuccess(room: FriendOrRoom) {
        this.room = room
        val transaction = supportFragmentManager.beginTransaction()
        transaction.replace(R.id.frame_layout, RoomCentreFragment.newInstance(room))
        transaction.commit()
    }

    /**
     * 邀请好友成功调用
     * */
    override fun onRoomInviteSuccess() {
        onHint("已发送邀请")
        onBackPressed()
        mPresenter!!.roomUser(room!!)
    }

    /**
     * 获取群聊用户成功调用
     * */
    override fun onRoomUserSuccess(owners: MutableList<FriendOrRoom>) {
        mOnToRoomCentreFragment!!.onRoomUser(owners)
    }

    /**
     * 退群成功调用
     * */
    override fun onRoomLeaveSuccess() {
        //删除数据
        ImApplication.appDatabase()
            .friendOrRoomDao().delete(room)
        val busData1 = EventBusData(
            Enumerate.Handle.list_chat, Enumerate.Action.list_delete, room
        )
        EventBus.getDefault().post(busData1)
        val busData2 = EventBusData(
            Enumerate.Handle.list_group, Enumerate.Action.list_delete, room
        )
        EventBus.getDefault().post(busData2)
        val intent = Intent(this, MainActivity::class.java)
        startActivity(intent)
        this.finish()
    }

    override fun onRoomKickSuccess() {
        onHint("已移除成员")
        onBackPressed()
        mPresenter!!.roomUser(room!!)
    }

}